<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/27/24
 * Time: 1:49 PM
 */

namespace App\Services;

use App\Models\WechatAccountChat;
use App\Models\WechatAccountCustomer;
use App\Models\WechatChatMsg;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Facades\Log;

class ChatService
{
    /**
     * 获取客户群列表
     *
     * @param $params
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getChatList($params)
    {
        $corpId     = $params['corp_id'] ?? '';
        $userId     = $params['user_id'] ?? '';
        $limit      = $params['limit'] ?? 20;
        $nextCursor = $params['next_cursor'] ?? '';

        try {
            $client   = new Client();
            $service  = new KfAccountService();
            $bodyData = [
                'owner_filter' => [
                    'userid_list' => [$userId]
                ],
                'limit'        => $limit
            ];
            if ($nextCursor) {
                $bodyData['cursor'] = $nextCursor;
            }
            $body     = [
                'headers'            => $service->headers,
                RequestOptions::JSON => $bodyData
            ];
            $token    = $service->getReplaceAccessToken($corpId);
            $response = $client->request(
                'POST',
                sprintf($service->api['chat_list'], $token),
                $body
            );
            if ($response->getStatusCode() != 200) {

                return [];
            }
            $contents = $response->getBody()->getContents();
            Log::info('获取客户群：', [$contents]);
            $data     = json_decode($contents, true);
            if ($data['errcode'] != 0) {

                return [];
            }
            if (!$chatList = $data['group_chat_list'] ?? []) {

                return [];
            }
            foreach ($chatList as &$item) {
                $chatItem = [];
                $res      = $client->request(
                    'POST',
                    sprintf($service->api['chat_detail'], $token),
                    [
                        'headers'            => $service->headers,
                        RequestOptions::JSON => [
                            'chat_id'   => $item['chat_id'] ?? '',
                            'need_name' => 1
                        ]
                    ]
                );
                if ($res->getStatusCode() != 200) {
                    $item['chat'] = $chatItem;
                }
                $con      = $res->getBody()->getContents();
                $itemData = json_decode($con, true);
                if ($itemData['errcode'] != 0) {
                    $item['chat'] = $chatItem;
                }
                $item['chat'] = $itemData['group_chat'] ?? [];
            }

            return [
                'has_more'    => isset($data['next_cursor']) ? 1 : 0,
                'next_cursor' => $data['next_cursor'] ?? '',
                'chat_list'   => $chatList
            ];
        } catch (\Exception $exception) {
            Log::error('获取客户群列表失败：' . $exception->getMessage());

            return [];
        }
    }


    /**
     * 获取消息列表
     *
     * @param $params
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getMsgList($params)
    {
        $corpId = $params['corp_id'] ?? '';
        $userId = $params['user_id'] ?? '';

        $list = WechatChatMsg::query()->where('corp_id', $corpId)->where('user_id', $userId)->orderBy('week', 'asc')->get();

        return $list->groupBy('week')->values();
    }


    /**
     * 更新群发送消息
     *
     * @param $params
     * @return bool
     */
    public function saveChatMsg($params)
    {
        $id          = $params['id'] ?? '';
        $corpId      = $params['corp_id'] ?? '';
        $week        = $params['week'] ?? 0;
        $chatType    = $params['chat_type'] ?? '';
        $userId      = $params['user_id'] ?? [];
        $content     = $params['content'] ?? '';
        $attachments = $params['attachments'] ?? [];

        if(!$week || !$userId) {

            return '请选择发送人和发送日期';
        }
        if (!$chatType) {

            return '请选择群发消息类型（发送给客户或者客户群）';
        }

        $chatMsg = $id ?
            WechatChatMsg::query()->find($id) :
            WechatChatMsg::query()->firstOrNew(['user_id' => $userId, 'week' => $week, 'chat_type' => $chatType]);

        $chatMsg->corp_id     = $corpId;
        $chatMsg->week        = $week;
        $chatMsg->user_id     = $userId;
        $chatMsg->chat_type   = $chatType;
        $chatMsg->content     = $content;
        $chatMsg->attachments = json_encode($attachments, JSON_UNESCAPED_UNICODE);

        return $chatMsg->save();
    }


    /**
     * 添加群发消息
     *
     * @param $params
     * @return bool|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function addChatMsg($params)
    {
        $corpId   = $params['corp_id'] ?? '';
        $userId   = $params['user_id'] ?? [];
        $week     = $params['week'] ?? 0;
        $chatType = $params['chat_type'] ?? 0;
        if (!$userId || !$week) {

            return '请选择发送人和发送日期';
        }
        if (!$chatType) {

            return '请选择群发消息类型（发送给客户或者客户群）';
        }
        $msg = WechatChatMsg::query()
            ->where('user_id', $userId)
            ->where('week', $week)
            ->where('chat_type', $chatType)
            ->first();
        if (!$msg) {

            return '发送消息不存在';
        }

        // $chatType = $msg->chat_type;

        try {
            $client   = new Client();
            $service  = new KfAccountService();
            $bodyData = [
                'chat_type' => $chatType,
                'sender'    => $userId,
            ];
            if ($chatType == 'single') {
                $userIds = WechatAccountCustomer::query()->where('account_id', $userId)->pluck('customer_id')->toArray();

                $bodyData['external_userid'] = $userIds;
            }
            if ($chatType == 'group') {
                $chatIds = WechatAccountChat::query()->where('user_id', $userId)->pluck('chat_id')->toArray();

                $bodyData['chat_id_list'] = $chatIds;
            }
            if ($content = $msg->content) {
                $bodyData['text'] = ['content' => $content];
            }
            if ($attachments = json_decode($msg->attachments, true)) {
                $bodyData['attachments'] = $attachments;
            }

            $body     = [
                'headers'            => $service->headers,
                RequestOptions::JSON => $bodyData
            ];
            $token    = $service->getReplaceAccessToken($corpId);
            $response = $client->request(
                'POST',
                sprintf($service->api['add_chat_msg'], $token),
                $body
            );
            if ($response->getStatusCode() != 200) {

                return false;
            }
            $contents = $response->getBody()->getContents();
            Log::info('请求添加群消息：', [$contents]);
            $data = json_decode($contents, true);
            if ($data['errcode'] != 0) {

                return false;
            }

            return true;
        } catch (\Exception $exception) {
            Log::error('添加群消息失败：' . $exception->getMessage());

            return false;
        }
    }
}
